<?php

namespace common\models\datas;

use common\components\behaviors\UpdateCacheBehavior;
use common\components\extenders\MenuManage;
use common\components\helpers\Fun;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\bootstrap\Html;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "{{%cate}}".
 *
 * @property integer $id
 * @property string $name
 * @property integer $type_id
 * @property integer $parent_id
 * @property string $arrparent_id
 * @property string $arrchild_id
 * @property string $pc_image
 * @property string $mobile_image
 * @property integer $sort
 * @property integer $is_child
 * @property integer $is_show
 * @property integer $created_at
 * @property string $description
 */
class Cate extends \common\components\bases\BaseModel
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%cate}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {

        return [
            [['type_id', 'parent_id', 'sort', 'is_child', 'is_show', 'created_at','module_id'], 'integer'],
            [['type_id', 'name','is_show',], 'required'],
            [['name'], 'string', 'max' => 100],
            [[ 'pc_image', 'mobile_image','wechat_banner','description'], 'string', 'max' => 255],
            [['arrparent_id', 'arrchild_id'], 'string', 'max' => 150],
            [['parent_id'], 'id_check', 'on' => ['update']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('common', '自动编号'),
            'name' => Yii::t('common', '分类名称'),
            'type_id' => Yii::t('common', '类型'),
            'parent_id' => Yii::t('common', '父级'),
            'arrparent_id' => Yii::t('common', '父级所有id（逗号隔开）'),
            'arrchild_id' => Yii::t('common', '子级所有id（逗号隔开）'),
            'pc_image' => Yii::t('common', 'pc端图标'),
            'mobile_image' => Yii::t('common', '移动端图标'),
            'sort' => Yii::t('common', '排序'),
            'is_child' => Yii::t('common', '是否有子级'),
            'is_show' => Yii::t('common', '是否显示'),
            'is_delete' => Yii::t('common', '是否删除'),
            'created_at' => Yii::t('common', '创建时间'),
            'updated_at' => Yii::t('common', '修改时间'),
            'wechat_banner' => Yii::t('common', '微信分类banner'),
            'module_id' => Yii::t('common', '三大模块'),
            'description' => Yii::t('common', '分类描述'),
        ];
    }

    public function fields()
    {
        $fields = parent::fields();
        $fields['is_show'] = function () {
            switch ($this->is_show) {
                case 0:
                    return \Yii::t('common', '不显示');
                case 1:
                    return \Yii::t('common', '显示');
            }
        };
        $fields['is_delete'] = function () {
            switch ($this->is_delete) {
                case 0:
                    return \Yii::t('common', '有效');
                case 1:
                    return \Yii::t('common', '删除');
            }
        };
        return $fields;
    }

    public function extraFields(){
        return [
            'type' => function(){
                return !empty($this->type) ? $this->type->name : '';
            },
            'backend_operate' => function () {
                return (new MenuManage(MenuManage::RECORD_ITEM_TOOLBAR, $this->attributes))->isDisable(
                    ['delete' => function ($data) {
                            return '';
                    },
                        'update' => function ($data) {
                            return '';
                        },
                        'create'=>function($data){
                            if($data['parent_id'] != 0){
                                return '<button style="color:#ffffff;border: none;padding: 1px 12px;border-radius:2px" type="button">添加子分类</button>';
                            }else{
                                return '';
                            }
                        }
                    ]
                )->create();
            }
        ];
    }

    /*保存操作后的操作*/
    public function afterSave($insert, $changedAttributes){
        parent::afterSave($insert, $changedAttributes);
        $data['Cate'] = $this->attributes;
        if($insert){//插入操作
            \Yii::$app->db->createCommand()->update("{{%cate}}",['arrchild_id'=>$this->id],"id={$this->id}")->execute();
            if($this->parent_id != 0){//当前元素的父节点不属于顶级分类元素
                Yii::$app->db->createCommand()->update("{{%cate}}",['is_child'=>1],"id={$this->parent_id}")->execute();//is_child不是是子分类的意思，而是whether have child,是否有子分类的意思T-T
                $rows = Cate::find()->where(['id'=>$this->parent_id])->one();//更改添加当前元素的父元素数组，包含了祖先元素
                Yii::$app->db->createCommand()->update("{{%cate}}",['arrparent_id'=>$rows['arrparent_id'].','.$this->parent_id], "id={$this->id}")->execute();
                $parentid_array = explode(',',$rows['arrparent_id'].','.$this->parent_id);
                foreach($parentid_array as $v){
                    if($v != 0){//不是顶级节点
                        $row = Cate::find()->where(['id'=>$v])->one();
                        if($row['arrchild_id'] != 0){
                            \Yii::$app->db->createCommand()->update("{{%cate}}", ['arrchild_id' => $row['arrchild_id'] . ',' . $this->id], "id={$v}")->execute();
                        }else {
                            \Yii::$app->db->createCommand()->update("{{%cate}}", ['arrchild_id' => $this->id], "id={$v}")->execute();
                        }
                    }
                }
            }
        }else{//是更新操作的话
            /*逻辑删除更新*/
            if(isset($changedAttributes['is_delete'])&& $changedAttributes['is_delete']!= 1 && $this->is_delete == 1){
                if($this->arrparent_id != "" && $this->arrparent_id != '0'){//不是顶级的父类
                    $parentid_array = explode(",", $this->arrparent_id);
                    foreach($parentid_array as $v){
                        if($v != 0){//具体的父类
                            $rows = Cate::find()->where(['id'=>$v])->one();
                            if($rows['arrchild_id'] != '' && $rows['arrchild_id'] != '0'){
                                $arr_arrchildid = explode(',',$rows['arrchild_id']);
                                $key = array_search($this->id, $arr_arrchildid);
                                unset($arr_arrchildid[$key]);
                                $new_arrchildid = implode(',',$arr_arrchildid);
                                \Yii::$app->db->createCommand()->update("{{%cate}}",['arrchild_id' => $new_arrchildid], "id={$v}")->execute();
                                if ($new_arrchildid == $v) {
                                    \Yii::$app->db->createCommand()->update("{{%cate}}", ['is_child' => 0], "id={$v}")->execute();
                                }
                            }
                        }
                    }
                }
            }

            if (isset($changedAttributes['sort']) && $changedAttributes['sort'] != $this->sort && isset($this->arrparent_id)) {
                $parent = Cate::find()->where(['id' => $this->parent_id])->one();
                if ($parent['parent_id'] == 0 && $this->parent_id != 0) {//该元素的父节点的父节点为0，但是钙元素的父节点不为0,就要加上顶级的0
                    \Yii::$app->db->createCommand()->update("{{%cate}}", ['arrparent_id' => '0,' . $parent['id']], "id={$this->id}")->execute();
                } elseif ($parent['parent_id'] != 0 && $this->parent_id != 0) {
                    \Yii::$app->db->createCommand()->update("{{%cate}}", ['arrparent_id' => $parent['arrparent_id'] . ',' . $parent['id']], "id={$this->id}")->execute();
                }
                if ($this->arrchild_id == 0) {//子数组是0
                    \Yii::$app->db->createCommand()->update("{{%cate}}", ['arrchild_id' => $this->id], "id={$this->id}")->execute();
                    \Yii::$app->db->createCommand()->update("{{%cate}}", ['arrchild_id' => $parent['arrchild_id'] . ',' . $this->id], "id={$this->parent_id}")->execute();
                } else {
                    if (!strpos($parent['arrchild_id'], (string)$this->id)) {
                        \Yii::$app->db->createCommand()->update("{{%cate}}", ['arrchild_id' => $parent['arrchild_id'] . ',' . $this->id], "id={$this->parent_id}")->execute();
                    }
                }
                $child = Cate::find()->where(['parent_id' => $this->id])->one();
                if ($child) {
                    \Yii::$app->db->createCommand()->update("{{%cate}}", ['is_child' => 1], "id={$this->id}")->execute();
                } else {
                    \Yii::$app->db->createCommand()->update("{{%cate}}", ['is_child' => 0], "id={$this->id}")->execute();
                }
            }
            if (isset($changedAttributes['parent_id']) && $changedAttributes['parent_id'] != $this->parent_id) {
                $rows = Cate::find()->where(['id' => $changedAttributes['parent_id']])->one();
                if ($rows['arrchild_id'] != '' && $rows['arrchild_id'] != '0') {
                    $arr_arrchildid = explode(',', $rows['arrchild_id']);
                    $key = array_search($this->id, $arr_arrchildid);
                    unset($arr_arrchildid[$key]);
                    $new_arrchildid = implode(',', $arr_arrchildid);
                    \Yii::$app->db->createCommand()->update("{{%cate}}", ['arrchild_id' => $new_arrchildid], "id={$rows['id']}")->execute();
                    $child = Cate::find()->where(['parent_id' => $rows['id']])->one();
                    if (empty($child)) {
                        \Yii::$app->db->createCommand()->update("{{%cate}}", ['is_child' => 0], "id={$rows['id']}")->execute();
                    } else {
                        \Yii::$app->db->createCommand()->update("{{%cate}}", ['is_child' => 1], "id={$rows['id']}")->execute();
                    }
                }
                $parent = Cate::find()->where(['id' => $this->parent_id])->one();
                \Yii::$app->db->createCommand()->update("{{%cate}}", ['arrchild_id' => $parent['arrchild_id'] . ',' . $this->arrchild_id, 'is_child' => 1], "id={$this->parent_id}")->execute();
                \Yii::$app->db->createCommand()->update("{{%cate}}", ['parent_id' => $this->parent_id, 'arrparent_id' => $parent['arrparent_id'] . ',' . $this->parent_id], "id={$this->id}")->execute();
            }
            //arrchildid排序
        }
    }

    /*删除之后的操作，但是我们执行的是逻辑删除，改的是is_delete的字段，所以不会真的删除不会执行这个命令*/
    public function afterDelete(){
        if($this->arrparent_id != "" && $this->arrparent_id != '0'){//不是顶级的父类
            $parentid_array = explode(",", $this->arrparent_id);
            foreach($parentid_array as $v){
                if($v != 0){//具体的父类
                    $rows = Cate::find()->where(['id'=>$v])->one();
                    if($rows['arrchild_id'] != '' && $rows['arrchild_id'] != '0'){
                        $arr_arrchildid = explode(',',$rows['arrchild_id']);
                        $key = array_search($this->id, $arr_arrchildid);
                        unset($arr_arrchildid[$key]);
                        $new_arrchildid = implode(',',$arr_arrchildid);
                       /* \Yii::error('a--------------------');
                        \Yii::error($new_arrchildid);
                        \Yii::error('d--------------------');*/
                        \Yii::$app->db->createCommand()->update("{{%cate}}",['arrchild_id' => $new_arrchildid], "id={$v}")->execute();
                        if ($new_arrchildid == $v) {
                            \Yii::$app->db->createCommand()->update("{{%cate}}", ['is_child' => 0], "id={$v}")->execute();
                        }
                    }
                }
            }
        }
    }

    public function getType(){
        return $this->hasOne(Type::className(),['id'=>'type_id']);
    }

    public function getCateAttr(){
        return $this->hasMany(CateAttr::className(),['cat_id'=>'id'])->onCondition(['site_id'=>Fun::getSiteId()]);
    }

    public function id_check($attribute)
    {
        if ($this->id == $this->parent_id) {
            $this->addError($attribute, Yii::t('backend', '不能选择自身分类作为父类'));
        }
//        elseif (strpos($this->arrchild_id, ',') != false) {
//            var_dump($this->arrchild_id);die;
//            $this->addError($attribute, Yii::t('backend', '无法修改存在子分类项的分类！'));
//        }
//        elseif($this->arrchild_id !== $this->id){
//            $this->addError($attribute, Yii::t('backend', '无法修改存在子分类项的分类！'));
//        }
    }

    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ],
            ],
            [
                'class' => UpdateCacheBehavior::className(),
                'cacheName' => 'cate',
                'fieldName' =>'type_id',
            ],
        ]);
    }
}
